package org.unisinos.gc.action;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.struts.action.Action;
import org.apache.struts.action.ActionError;
import org.apache.struts.action.ActionErrors;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
import org.unisinos.gc.dao.UsuarioDAO;
import org.unisinos.gc.form.LoginForm;
import org.unisinos.gc.vo.Usuario;

public class LoginAction extends Action {

	@Override
	public ActionForward execute(ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response)
			throws Exception {
		
		ActionForward forward = mapping.findForward("success");
		ActionErrors errors = new ActionErrors();
		
		try {
			LoginForm loginForm = (LoginForm)form;
			Usuario usuario = null;
			if ("true".equals(request.getParameter("logout"))) {
				loginForm.setUsuario("");
				loginForm.setSenha("");
			}else {
				
				usuario = UsuarioDAO.getUsuario(loginForm.getUsuario(), loginForm.getSenha());
				if (usuario == null) {
					errors.add(ActionErrors.GLOBAL_ERROR, new ActionError("invalidUser"));
				}
			}
			request.getSession().setAttribute("usuarioLogado", usuario);
			
		}catch (Exception e) {
			e.printStackTrace();
			errors.add(ActionErrors.GLOBAL_ERROR, new ActionError("systemError"));
		}
		
		if (!errors.isEmpty()) {
			super.saveErrors(request, errors);
			forward = mapping.findForward("error");
		}
		
		return forward;
		 
	}

}
